package com.zut.chat.controller;

import com.zut.chat.entity.ChatMessage;
import com.zut.chat.entity.SysUser;
import com.zut.chat.entity.User;
import com.zut.chat.service.ChatMessageService;
import com.zut.chat.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台管理系统控制器
 */
@RestController
@RequestMapping("/api/backend")
@CrossOrigin(origins = "*")
public class BackendController {

    @Autowired
    private UserService userService;

    @Autowired
    private ChatMessageService chatMessageService;
    
    /**
     * 检查管理员登录状态
     */
    private ResponseEntity<?> checkAdminAuth(HttpSession session) {
        SysUser adminUser = (SysUser) session.getAttribute("adminUser");
        if (adminUser == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "请先登录管理员账号");
            errorResponse.put("code", 401);
            return ResponseEntity.status(401).body(errorResponse);
        }
        return null;
    }

    /**
     * 获取所有用户列表（分页）
     */
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String userType,
            HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        
        try {
            List<User> users;
            
            if (nickname != null && !nickname.trim().isEmpty()) {
                users = userService.searchUsersByNickname(nickname.trim());
            } else if (userType != null && !userType.trim().isEmpty()) {
                users = userService.getUsersByType(User.UserType.valueOf(userType.toUpperCase()));
            } else {
                users = userService.getAllUsers();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", users);
            response.put("total", users.size());
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取用户列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取聊天消息列表（分页）
     */
    @GetMapping("/messages")
    public ResponseEntity<?> getAllMessages(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size,
            @RequestParam(required = false) String senderNickname,
            @RequestParam(required = false) String messageType,
            HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        
        try {
            List<ChatMessage> messages = chatMessageService.getMessagesForBackend(
                page, size, senderNickname, messageType);

            long totalCount = chatMessageService.getTotalMessageCount();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", messages);
            response.put("total", totalCount);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取消息列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 设置用户为管理员
     */
    @PostMapping("/users/{sessionId}/set-admin")
    public ResponseEntity<?> setUserAsAdmin(@PathVariable String sessionId, HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        try {
            User user = userService.findBySessionId(sessionId);
            if (user == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            boolean success = userService.setUserAsAdmin(sessionId);
            
            if (success) {
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("success", true);
                successResponse.put("message", "用户 " + user.getNickname() + " 已设置为管理员");
                return ResponseEntity.ok(successResponse);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "设置管理员失败");
                return ResponseEntity.status(500).body(errorResponse);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "设置管理员失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 取消管理员权限
     */
    @PostMapping("/users/{sessionId}/remove-admin")
    public ResponseEntity<?> removeUserAdmin(@PathVariable String sessionId, HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        try {
            User user = userService.findBySessionId(sessionId);
            if (user == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            user.setUserType(User.UserType.NORMAL);
            userService.updateById(user);

            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("success", true);
            successResponse.put("message", "用户 " + user.getNickname() + " 的管理员权限已取消");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "取消管理员权限失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{sessionId}")
    public ResponseEntity<?> deleteUser(@PathVariable String sessionId, HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        try {
            User user = userService.findBySessionId(sessionId);
            if (user == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            userService.removeById(user.getId());

            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("success", true);
            successResponse.put("message", "用户 " + user.getNickname() + " 已删除");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "删除用户失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/messages/{messageId}")
    public ResponseEntity<?> deleteMessage(@PathVariable Long messageId, HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        try {
            ChatMessage message = chatMessageService.getById(messageId);
            if (message == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "消息不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            chatMessageService.removeById(messageId);

            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("success", true);
            successResponse.put("message", "消息已删除");
            return ResponseEntity.ok(successResponse);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "删除消息失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取系统统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<?> getSystemStats(HttpSession session) {
        
        // 检查登录状态
        ResponseEntity<?> authCheck = checkAdminAuth(session);
        if (authCheck != null) {
            return authCheck;
        }
        try {
            long totalUsers = userService.count();
            long onlineUsers = userService.getOnlineUserCount();
            long totalMessages = chatMessageService.getTotalMessageCount();
            long todayMessages = chatMessageService.getTodayMessageCount();
            long adminCount = userService.getAdminCount();

            Map<String, Object> stats = new HashMap<>();
            stats.put("totalUsers", totalUsers);
            stats.put("onlineUsers", onlineUsers);
            stats.put("totalMessages", totalMessages);
            stats.put("todayMessages", todayMessages);
            stats.put("adminCount", adminCount);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取统计信息失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
} 